package com.hnkywl.sts.service.cwgl;

import com.google.gson.Gson;
import com.hnkywl.sts.dao.cwgl.CwsfDao;
import com.hnkywl.sts.dao.cwgl.KmdmDao;
import com.hnkywl.sts.dao.organ.GsjgDao;
import com.hnkywl.sts.entity.cggl.Jsd;
import com.hnkywl.sts.entity.cwgl.*;
import com.hnkywl.sts.entity.sfgl.Sfk;
import com.hnkywl.sts.entity.sys.Yg;
import com.hnkywl.sts.entity.zjgl.Pj;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.util.BaseUtils;
import net.ruixin.orm.hibernate.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-5-14
 * Time: 上午9:47
 * To change this template use File | Settings | File Templates.
 */
@Service
public class CwsfService {
    private CwsfDao cwsfDao;
    private KmdmService kmdmService;
    private GsjgDao gsjgDao;
    private KmdmDao kmdmDao;


    //查询财务收付列表
    public String findAllCwsf(Integer sfklx,String zt,String bm, Date sfkrqStart,Date sfkrqEnd,String sbgs, Long sbgsId, String gldwMc,String cwsfpjlxMc,Integer cwsfZt,int pageNo, int pageSize) {
        Long nbgsIds = null;
        if(sbgsId !=null && sbgs.equals(gsjgDao.get(sbgsId).getJc())){
            nbgsIds = nbgsIds;
        }
        Page<Sfk> sfkPage = this.cwsfDao.findCwsfList(sfklx, zt, bm, sfkrqStart,sfkrqEnd, sbgs, nbgsIds, gldwMc,  cwsfpjlxMc,cwsfZt,pageNo, pageSize);;
        List<Sfk> sfkList = sfkPage.getResult() == null ? new ArrayList<Sfk>() : sfkPage.getResult();
        if(sfkList.size()>0){
            sfkList = getCzztByPj(sfkList);
        }
        String sfkJson = BaseUtils.fetchCollectionToJson(sfkList, "id", "bm", "sfkrq", "sfklx", "gldw.qc", "sfje", "pjlx.z", "glkhh.qc","kxlx", "czzt","sbgs.jc", "shr.xm","voucherNum","nbkhh.qc");
        return "{\"total\":" + sfkPage.getTotalCount() + ",\"rows\":[" + sfkJson + "]}";
    }

    public List<Sfk> getCzztByPj(List<Sfk> sfkList){
        for(Sfk p:sfkList){
            String czzt = "";
            if(p.getInsertFlag()==1 && p.getDeleteFlag()==1){
                czzt = "wdr";
            }else if(p.getInsertFlag()==1 && p.getDeleteFlag()==3){
                czzt = "sccg";
            }else if(p.getInsertFlag()==3 && p.getDeleteFlag()==1){
                czzt = "drcg";
            }else if(p.getInsertFlag()==2 && p.getDeleteFlag()==1 ||p.getInsertFlag()==2 && p.getDeleteFlag()==3 ){
                czzt = "drsb";
            }else if(p.getInsertFlag()==3 && p.getDeleteFlag()==2){
                czzt = "scsb";
            }else{
                czzt = "null";
            }
            p.setCzzt(czzt);
        }
        return sfkList;
    }

    @Transactional
    public Map getVoucher(Long id, String uuid, List<VoucherItemData> voucherItemDataList) {
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String systemDate =simple.format(new Date());
        Sfk cwsf = this.cwsfDao.get(id);
        Map<String, Object> result = new HashMap<String, Object>();
        List<Map> list = this.cwsfDao.getVoucher(cwsf);
        DecimalFormat df = new DecimalFormat("#.##");
        int order = 1;
        for(Map m : list){
            m.put("id",order);//唯一标识
            m.put("vchrid", uuid);//凭证主表ID
            m.put("itemorder", order);//分录编号
            m.put("bizdate", systemDate);//业务日期
            m.put("qty", m.get("qty") != null ? m.get("qty") : 0);//数量
            m.put("debit", m.get("debit") != null ? df.format(m.get("debit")) : 0.00);//借方金额
            m.put("credit", m.get("credit") != null ? df.format(m.get("credit")) : 0.00);//贷方金额
            m.put("orgnd", m.get("orgnd") != null ? df.format(m.get("orgnd")) : 0.00);//借方原币
            m.put("orgnc", m.get("orgnc") != null ? df.format(m.get("orgnc")): 0.00);//贷方原币
            order++;
//            m.put("id", order);//唯一标识
//            m.put("vchrid", uuid);//凭证主表ID
//            m.put("itemorder", order);//分录编号
//            m.put("subjectcode", m.get("subjectcode") != null && m.get("subjectcode") != null ? m.get("subjectcode") : "");//科目代码
//            m.put("subjectname", m.get("subjectname") != null && m.get("subjectname") != null ? m.get("subjectname") : "");//科目名称
//            m.put("debit", m.get("debit") != null ? df.format(m.get("debit")) : 0.00);//借方金额
//            m.put("credit", m.get("credit") != null ? df.format(m.get("credit")) : 0.00);//贷方金额
//            m.put("qty", m.get("qty") != null ? m.get("qty") : 0);//数量
//            m.put("price", 0);//单价
//            m.put("currencycode", "CNY");//货币代码
//            m.put("exchrate", 1.000000);//汇率
//            m.put("orgnd", m.get("debit") != null ? df.format(m.get("debit")) : 0.00);//借方原币
//            m.put("orgnc", m.get("credit") != null ? df.format(m.get("credit")): 0.00);//贷方原币
//            m.put("settlementcode",""); //结算方式代码
//            m.put("settlementno", ""); //结算号
//            m.put("bizdate", simple.format(new Date()));//业务日期
//            m.put("digest", m.get("digest")!= null ? m.get("digest") : "");//摘要
//            m.put("bizno", "");//业务号
//            m.put("suppliername",  m.get("suppliername") != null ?  m.get("suppliername") : "");//供应商名称
//            m.put("suppliercode",  m.get("suppliercode") != null ?  m.get("suppliercode") : "");//供应商代码
//            m.put("departmentname",  m.get("departmentname") != null ?  m.get("departmentname") : "");//部门名称
//            m.put("departmentcode",  m.get("departmentcode") != null ?  m.get("departmentcode") : "");//部门代码
//            m.put("customername",  m.get("customername") != null ?  m.get("customername") : "");//客户名称
//            m.put("customercode",  m.get("customercode") != null ?  m.get("customercode") : "");//客户代码
//            m.put("staffname",  m.get("staffname") != null ?  m.get("staffname") : "");//职员名称
//            m.put("staffcode",  m.get("staffcode") != null ?  m.get("staffcode") : "");//职员代码
//            list.add(m);
//            order++;
        }
        result.put("items", list);
        return result;
    }


    /**
     * 获取U8凭证分录信息
     *
     * @param id
     * @param uuid
     * @return
     */
    @Transactional
    public Map getU8VoucherItems(Long id, String uuid,List<VoucherItemData> voucherItemDataList,Date documentDate) {
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
        String systemDate =simple.format(new Date());
        Sfk cwsf = this.cwsfDao.get(id);
        Map<String, Object> result = new HashMap<String, Object>();
        List<Map> list = this.cwsfDao.getVoucher(cwsf);
        DecimalFormat df = new DecimalFormat("#.##");
        //凭证分录信息
        List<Map> items = new ArrayList<Map>();
        int order = 1;
        for(Map m : list){
                Map<String, Object> voucherItem = new HashMap<String, Object>();
                //voucherItem.put("id", order);//唯一标识
                //voucherItem.put("vchrid", uuid);//凭证主表ID
                voucherItem.put("entry_id", order);//分录编号
                voucherItem.put("account_code", m.get("account_code") != null ? m.get("account_code") : "");//科目代码
//                voucherItem.put("subjectname", item.getKmdm() != null && item.getKmmc() != null ? item.getKmmc() : "");//科目名称
                voucherItem.put("natural_debit_currency", m.get("natural_debit_currency") != null ? df.format(m.get("natural_debit_currency")) : "0.00");//借方金额
                voucherItem.put("natural_credit_currency", m.get("natural_credit_currency")!= null ? df.format(m.get("natural_credit_currency")) : "0.00");//贷方金额
//                voucherItem.put("qty", item.getSl() != null ? item.getSl() : 0);//数量
                voucherItem.put("unit_price", "0");//单价,在科目有数量核算时，填写此项
                voucherItem.put("debit_quantity", "0");//借方数量,在科目有数量核算时，填写此项
                voucherItem.put("credit_quantity", "0");//贷方数量,在科目有数量核算时，填写此项
                voucherItem.put("currency", "CNY");//货币代码
                voucherItem.put("exchange_rate2", "1.000000");//汇率
//                voucherItem.put("orgnd", item.getJfje() != null ? df.format(item.getJfje()) : "0.00");//借方原币
//                voucherItem.put("orgnc", item.getDfje() != null ? df.format(item.getDfje()) : "0.00");//贷方原币
                voucherItem.put("settlement", "");//结算方式,在科目是银行或往来时，可以填写此项
                voucherItem.put("document_id", "");//票据号，在科目是银行或往来时，可以填写此项
                voucherItem.put("document_date",systemDate);//票据日期，在科目是银行或往来时，可以填写此项
                voucherItem.put("abstract", m.get("abstract") != null ? m.get("abstract") : "");//摘要
//                voucherItem.put("bizno", "");//业务号
            Map<String, String> fzhsMap = new HashMap<String, String>();
            Map<String, Map> xjllxmMap = new HashMap<String, Map>();
            fzhsMap =  this.findFzhsByMap(cwsf,m,fzhsMap,xjllxmMap);
            voucherItem.put("auxiliary_accounting", fzhsMap);
            voucherItem.put("cash_flow", xjllxmMap);
            items.add(voucherItem);
            order++;
        }
        result.put("items", items);
        return result;
    }

    @Transactional
    public void cwsfChangeDrrq(Long cwsfId,Date date){
        Sfk cwsf = this.cwsfDao.get(cwsfId);
        cwsf.setDrrq(date);
        cwsfDao.save(cwsf);
    }

    private Map<String,String > findFzhsByMap(Sfk sfk, Map<Object,String> map,Map<String, String> fzhsMap, Map<String, Map> xjllxmMap){
        DecimalFormat df = new DecimalFormat("#.##");
        //1.更具公司还有代码查询科目代码
        Kmdm kmdm = kmdmDao.findKmdmDetailByGs(sfk.getSbgs().getId(),map.get("account_code"));
        if(kmdm==null){
            kmdm = kmdmDao.findKmdmDetailByGs(YgService.getCurrentYgZgGsId(),map.get("account_code"));
        }
        //2.现金流量项目
        if(kmdm!=null&& kmdm.getXjllsx() !=null && !"".equals(kmdm.getXjllsx()) &&  kmdm.getXjllsx().equals("Y")){
            if(sfk.getSfklx()==1 ||sfk.getSfklx()==2){
                fzhsMap.put("item_id", "04");
            }else{
                fzhsMap.put("item_id", "01");
            }
            Map value = new HashMap<String, Double>();
            Double d = map.get("natural_debit_currency") != null ? Double.parseDouble(df.format(map.get("natural_debit_currency"))):0.00 ;
            Double c = map.get("natural_credit_currency") != null ? Double.parseDouble(df.format(map.get("natural_credit_currency"))):0.00;
            value.put("debit", d);
            value.put("credit", c);
            value.put("md", Math.abs(d - c));
            value.put("ccode", map.get("account_code"));
            if(sfk.getSfklx()==1 ||sfk.getSfklx()==2){
                xjllxmMap.put("04", value);
            }else{
                xjllxmMap.put("01", value);
            }
        }//3.其他项目
        else  if(kmdm !=null && kmdm.getTyfzhsmc()!=null && kmdm.getTyfzhsys() != null ){
            fzhsMap.put("item_id",kmdm.getTyfzhsys().getCode() );
        }
        else{
            if(map.get("dept_id") !=null && !map.get("dept_id").toString().equals("")){
                fzhsMap.put("dept_id",map.get("dept_id"));
            }
            if(map.get("personnel_id") !=null && !map.get("personnel_id").toString().equals("")){
                fzhsMap.put("personnel_id",map.get("personnel_id"));
            }
            if(map.get("cust_id") !=null && !map.get("cust_id").toString().equals("")){
                fzhsMap.put("cust_id",map.get("cust_id"));
            }
            if(map.get("supplier_id") !=null && !map.get("supplier_id").toString().equals("")){
                fzhsMap.put("supplier_id",map.get("supplier_id"));
                fzhsMap.put("operator","-");
            }
        }
        return fzhsMap;
    }


    //财务收付分录
    @Transactional
    public String findCwsfFl(Long id) {
        Sfk cwsf = this.cwsfDao.get(id);
        List<Map> list = this.cwsfDao.getVoucher(cwsf);
        List<Map> txcdJson = new ArrayList<Map>();
        for (int i =0;i<list.size() ;  i++){
            Map<String, Object> voucherItem = (Map<String, Object>)list.get(i);
            voucherItem.put("zy",voucherItem.get("digest"));
            voucherItem.put("km",voucherItem.get("subjectname"));
            voucherItem.put("jf",voucherItem.get("debit"));
            voucherItem.put("df",voucherItem.get("credit"));
            txcdJson.add(voucherItem);
        }
        return new Gson().toJson(txcdJson);
    }

    //获取附单据数
    public String getFzhsByCode(Long gsId,String code){
        return this.kmdmService.findKmdmDetailByGs(gsId,code).getFzhslx();
    }

    @Transactional
    public Map getVoucherMaster(Long id, Integer attachment, String uuid, String year, String mouth, Yg yg) {
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
        String systemDate =simple.format(new Date());
        Map<String, Object> voucherMaster = new HashMap<String, Object>();
        Sfk cwsf = this.cwsfDao.get(id);
        voucherMaster.put("id", uuid);
        voucherMaster.put("vchrtypecode", "记");//凭证类别
        voucherMaster.put("acctyear", year != null ? year : "");//会计年度
        voucherMaster.put("acctperiod", mouth != null ? mouth : "");//会计期间
        voucherMaster.put("createdate", systemDate);//凭证日期
        voucherMaster.put("unitcode", cwsf.getCreateOrgan() != null && cwsf.getCreateOrgan().getJiuqiUnitCode() != null ? cwsf.getCreateOrgan().getJiuqiUnitCode() : "");//组织机构代码
        voucherMaster.put("acctbookcode", "01");//账薄标识
        voucherMaster.put("createuser", yg.getXm());//制单人
        voucherMaster.put("attachment", attachment);//附件张数
        voucherMaster.put("memo", "");//备注
        voucherMaster.put("companyId", this.findCwsfDetail(id).getSbgs().getId());//公司ID
        return voucherMaster;
    }

    @Transactional
    public Map getRevokeInfo(Long id) {
        Map<String, Object> revokeInfo = new HashMap<String, Object>();
        Sfk result = cwsfDao.get(id);
        if (result == null) {
            throw new RuntimeException("未获取凭证信息!");
        }
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("MM");
        revokeInfo.put("id", result.getUuid());//凭证ID
        revokeInfo.put("vchrid", result.getVoucherId());//凭证ID
        revokeInfo.put("unitcode",result.getCreateOrgan() != null && result.getCreateOrgan().getJiuqiUnitCode() != null ? result.getCreateOrgan().getJiuqiUnitCode() : "");//单位代码
        revokeInfo.put("vchrtypecode", "记");//会计年度
        revokeInfo.put("acctyear", result.getAcctyear());//会计年度
        revokeInfo.put("acctperiod",simpleDateFormat3.format(result.getDrrq()));//会计年度
        revokeInfo.put("vchrnum", result.getVoucherNum());//凭证号

        return revokeInfo;
    }
//    @Transactional
//    public String revokeNote(Long id,Integer revokeType,Long userId) {
//        String error = null;
//        try {
//            error = this.cwsfDao.revokeNote(id, revokeType, userId);
//        } catch (Exception e) {
//            e.printStackTrace();
//            error = e.getMessage();
//        }
//        return error;
//    }

    //查询收付款明细
    @Transactional
    public Sfk findCwsfDetail(Long id) {
        return this.cwsfDao.get(id);
    }

    @Autowired
    public void setCwsfDao(CwsfDao cwsfDao) {
        this.cwsfDao = cwsfDao;
    }

    @Autowired
    public void setKmdmService(KmdmService kmdmService) {
        this.kmdmService = kmdmService;
    }
    @Autowired
    public void setGsjgDao(GsjgDao gsjgDao) {
        this.gsjgDao = gsjgDao;
    }
    @Autowired
    public void setKmdmDao(KmdmDao kmdmDao) {
        this.kmdmDao = kmdmDao;
    }
}
